【问题标题】:Why after compile c++ code with -O3 flag function generate wrong output? [closed]为什么使用 -O3 标志函数编译 c++ 代码后会产生错误的输出? [关闭]
【发布时间】:2015-11-01 14:09:47
【问题描述】:

当我在主函数中写

  Function fun;
  fun.AddName("string1");
  std::cout << fun.GetNumberOfIndeks();

我在屏幕上看到两个不同的数字:

  • 1(错误)当 g++ 有 -O3 标志时
  • 0 当 g++ 有 -O0 标志时

类和方法的定义如下:

class IFunction
{
   public:
     virtual void AddName(std::string nazwa_funkcji) = 0;
     virtual std::size_t GetNumberOfIndeks() = 0;
};

class Function: public IFunction 
{
    public:
       Function();
      void AddName(std::string nazwa_funkcji);
       std::size_t   GetNumberOfIndeks();

    private:
       std::vector<std::unique_ptr<std::string>> vp_nazwy_indeksow_;
       std::unique_ptr<::std::string> p_nazwa_;
}

Function::Function():p_nazwa_(new std::string(""))
{

}

std::size_t Function::GetNumberOfIndeks()
{
    vp_nazwy_indeksow_.size();
}

void Function::AddName(std::string nazwa_funkcji)
{
    std::unique_ptr<::std::string> pl_nazwa_funkcji (new std::string(nazwa_funkcji));
    p_nazwa_ = std::move(pl_nazwa_funkcji);
}

当我评论第二行时

Function fun;
//fun.AddName("string1");
std::cout << egzFunkcji3.GetNumberOfIndeks();

我在屏幕上看到带有 g++ 标志 -O3 的预期 问题出在哪里?

【问题讨论】:

  • 如果您不向我们展示一半的代码,并且您展示的代码中包含缺少分号等基本语法错误,您希望我们如何回答这个问题?
  • 为了清楚起见,我没有显示所有代码..我还从类 Function 中删除了一些方法。对不起表单错误。
  • 清晰度很好。但是你砍的太多了。
  • 请发MCVE
  • 从头开始。第一件事。将“-Wall -Werror”添加到您的编译器标志中。

标签: c++ g++ compiler-optimization


【解决方案1】:

这是你的功能:

std::size_t Function::GetNumberOfIndeks() {
    vp_nazwy_indeksow_.size();
}

我计算零返回语句会导致未定义的行为。

如果您的编译器没有对此发出警告或错误,那么您的编译器就是垃圾,应该更换为更好的编译器。

【讨论】:

  • 谢谢!!!。我尝试使用命令 >g++-4.9 -std=c++11 Function.cpp main.cpp 或 >g++-4.8 -std=c++11 Function.cpp main.cpp 编译上面的简单代码,编译器什么也没告诉我关于缺少退货声明。奇怪的事情。
  • 我强烈推荐使用-Wall -Werror。 gcc 4.8 将提供带有这些标志的错误。 coliru.stacked-crooked.com/a/b44400014438a4a6
猜你喜欢
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
相关资源
最近更新 更多