Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

传值和传常量引用,在作为公共接口时有区别吗? #3

Closed
tnie opened this issue Mar 27, 2018 · 2 comments
Closed

传值和传常量引用,在作为公共接口时有区别吗? #3

tnie opened this issue Mar 27, 2018 · 2 comments

Comments

@tnie
Copy link
Owner

tnie commented Mar 27, 2018

void hello(std::string name);
void hello(const std::string& name);  // std::string const * const 

后者不会造成跨模块管理内存,前者呢?——运行时报错 __acrt_first_block == header

std::string hello(void);

会产生「跨模块内存管理」问题吗?——会

std::string& hello(void)

返回引用呢?——不会,但需要注意引用本体的生存周期

tnie added a commit that referenced this issue Mar 27, 2018
@tnie tnie closed this as completed Mar 27, 2018
@tnie
Copy link
Owner Author

tnie commented Apr 18, 2018

void hello(std::string* pstr);

会产生「跨模块内存管理」问题吗?——会!在跨模块中显式调用 resize() ,程序必然崩溃 __acrt_first_block == header

ps

突然想起来 《Google C++ 编程规范》中硬性约定:

所有按引用传递的参数必须加上 const

string 作为输出参数时只能用 string*

void Foo(const string& in, string* out);

不过,在论述为什么坚持上述约定时,未提到跨模块管理内存的梗,只是单纯地描述:

引用在语法上是值却拥有指针的语义,容易引起误解。

@tnie
Copy link
Owner Author

tnie commented Jun 19, 2018

试验结果

// 作为输入
_ADD_API void helloValue(std::string name);                 // ×
_ADD_API void helloRef(const std::string& name);            //
_ADD_API void helloPointer(const std::string* const name);  // 〇 满足功能,比较丑而已
// 作为输出
_ADD_API std::string  returnValue(void);                    // ×
_ADD_API std::string& returnRef(void);                      // 〇 功能不完善,需要保证引用源有效
_ADD_API bool returnPointer(std::string* out);              // ×
_ADD_API bool returnSmartPtr(std::shared_ptr<std::string> out);              // ×
_ADD_API bool returnSmartPtr2(std::shared_ptr<std::string>& out);            // ×
_ADD_API bool returnSmartPtr3(const std::shared_ptr<std::string>& out);      // ×

_ADD_API bool fillv(std::shared_ptr<std::vector<std::string>>& out);          // ×
_ADD_API std::shared_ptr<std::vector<std::string>> returnv();                 // ×

结论

  • 输入参数必须是常量引用的 stl/string
  • 输出参数无法使用 stl/string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant