gpt4 book ai didi

c++ - 返回拷贝而不是 const 引用时我会破坏代码吗

转载 作者:太空狗 更新时间:2023-10-29 20:28:24 25 4
gpt4 key购买 nike

我需要使用的框架定义了一个简单的互斥量类,它可以存储互斥量所有者的名称以帮助调试:

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 的答案感兴趣。

最佳答案

按值返回的那个可能会抛出一个错误的分配,引用那个是不抛出的。所以这可能是个问题。

此外,它们有可能调用不同的重载,并且 traits 会以不同的方式专门化,但我不担心这一点。

关于c++ - 返回拷贝而不是 const 引用时我会破坏代码吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com