我需要使用的框架定义了一个简单的互斥体类,它可以存储互斥体所有者的名称以帮助调试:
class mutex
{
public:
explicit mutex(const std::string& mutex_owner = "");
bool acquire() const;
bool release() const;
const std::string& get_name() const {return owner_name_;}
// ...
private:
std::string owner_name_;
// ...
};
我刚刚更改了一些算法,使互斥类型成为模板参数,以便我可以出于性能原因传入这个,如果不需要锁定:
class non_mutex
{
public:
explicit non_mutex(const std::string& mutex_owner = "") {}
bool acquire() const {return true;}
bool release() const {return true;}
std::string get_name() const {return "";}
};
由于这个不存储名称(无需调试),我更改了
get_name()
成员函数以返回 std::string
,而不是 const std::string&
。现在我的问题是:这( 默默地 )会破坏任何东西吗?代码编译得很好,似乎也运行得很好,但是这个代码库中很少有测试,而且这个函数主要只在出现问题时使用,而不是经常使用。
此更改可能触发运行时故障的情况有哪些?
请注意,这是一个 C++03 环境,但我也对 C++11 的答案感兴趣。
最佳答案
按值返回的一个可能会抛出一个错误的分配,引用一个是不抛出的。所以这可能是一个问题。
此外,他们有可能调用不同的重载,特征会以不同的方式专门化,但我不会担心这一点。
关于c++ - 返回拷贝而不是常量引用时我会破坏代码吗,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13342016/