小编Fra*_*ank的帖子

为什么这个被零除错误只出现在优化代码中?

我刚刚发现了一个奇怪的错误,只有在启用优化时才会发生错误(g++ -O2).它是Arithmetic exception在以下代码中,当interval设置为零时(从命令行参数):

for(int i = 0; i < n; ++i) {
  if((i + 1) % interval == 0) { // exception here
    DoSomething();
  }
}
Run Code Online (Sandbox Code Playgroud)

很明显,模零操作会抛出一个被零除的异常,但为什么只有在代码编译时才会启用优化?

c++ compiler-construction optimization divide-by-zero

3
推荐指数
1
解决办法
1957
查看次数

通过替换从另一个字符串变量定义?

我有时需要两个字符串变量,其中第二个变量的值来自第一个字符替换.

有没有比下面显示的更简洁的方法呢?使用两个单独的命令来定义第一个var来自第一个变量很容易出错并且很麻烦:

# Example: "pstopdf" and "ps2pdf":
my $name1 = "pstopdf";
my $name2 = $name1;
$name2 =~ s/to/2/;   
Run Code Online (Sandbox Code Playgroud)

perl

3
推荐指数
1
解决办法
118
查看次数

交错文本文件内容的最Pythonic方式是什么?

Python问题:

如果我有一个文件列表,如何从每个文件打印#1行,然后打印#2行等?(我是一个Python新手,显然......)

例:

file1:
foo1
bar1

file2:
foo2
bar2

file3:
foo3
bar3
Run Code Online (Sandbox Code Playgroud)

功能调用:

names = ["file1", "file2", "file3"]
myfct(names)
Run Code Online (Sandbox Code Playgroud)

期望的输出:

foo1
foo2
foo3

bar1
bar2
bar3
Run Code Online (Sandbox Code Playgroud)

这就是我做到的,但我确信有更优雅的Pythonic方式:

def myfct(files):
    file_handlers = []
    for myfile in files:
        file_handlers.append(open(myfile))
    while True:
        done = False
        for handler in file_handlers:
            line = handler.readline()
            eof = len(line) == 0 # wrong
            if (eof):
                done = True
                break
            print(line, end = "")
        print()
        if done == True:
            break
Run Code Online (Sandbox Code Playgroud)

PS:我正在使用Python 2.6 from __future__ import print_function.

python

3
推荐指数
1
解决办法
489
查看次数

如何在uint64_t中移位> = 32位?

以下代码触发gcc警告(gcc 4.2.1):

#include <boost/cstdint.hpp>
boost::uint64_t x = 1 << 32; // warning: left shift count >= width of type
Run Code Online (Sandbox Code Playgroud)

不应该没问题,因为该类型有64位?

c++ bit-manipulation

3
推荐指数
1
解决办法
3077
查看次数

如何在python中传递包含单个字符串的列表?

在Python中,如何传递仅包含一个字符串的列表?

例如:

def fn(mylist): return len(mylist)
print fn(('abc', 'def')) # prints 2
print fn(('abc'))        # prints 3
Run Code Online (Sandbox Code Playgroud)

我希望它打印1列表中的一个字符串,('abc') 而是打印3字符串的3个字符.

python

3
推荐指数
2
解决办法
5267
查看次数

为什么在Base类而不是Derived类上调用virtual operator ==?

virtual operator==Base班上定义了一个.但出于某种原因,它似乎并没有真正被视为虚拟.

请参阅此示例代码:

#include <iostream>
#include <boost/unordered_set.hpp>

template<class T> struct EqualByValue {
  bool operator()(T const* a, T const* b) const { return *a == *b; }
};

struct Base {
  virtual bool operator==(Base const& other) const {
    std::cerr << "Base==" << std::endl;
  }
};

struct Derived : Base {
  virtual bool operator==(Derived const& other) const {
    std::cerr << "Derived==" << std::endl;
  }
};

int main(int argc, char** argv){
  typedef boost::unordered_set<Base*, boost::hash<Base*>, EqualByValue<Base> > 
    MySet;
  MySet s; …
Run Code Online (Sandbox Code Playgroud)

c++ equality operator-keyword

3
推荐指数
1
解决办法
367
查看次数

如何从std :: istream中读取(使用operator >>)?

我如何阅读std::istream使用operator>>

我尝试了以下方法:

void foo(const std::istream& in) {
  std::string tmp;
  while(in >> tmp) {
     std::cout << tmp;
  }
}
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误:

error: no match for 'operator>>' in 'in >> tmp'
Run Code Online (Sandbox Code Playgroud)

c++ operators istream extraction-operator

2
推荐指数
1
解决办法
1605
查看次数

要获得引用计数,我是否必须使用shared_ptr来混淆我的API?

我最近有以下内存错误,这很容易在这里找到,但在更复杂的代码中可能更难检测:

class Foo : public IFoo {
  const Bar& bar_;
public:
  Foo(const Bar& bar) : bar_(bar) {
  }
  void test() {
    // access bar_ here
  }
};

int baz() {
  IFoo* foo = NULL;
  if(whatever) {
    Bar bar;
    foo = new Foo(bar);
  }
  else {
    // create other foo's
  }
  foo->test(); // segmentation fault
}
Run Code Online (Sandbox Code Playgroud)

错误是Bar立即超出范围,被销毁然后使用foo->test().一种解决方案是Bar使用在堆上创建Bar* bar = new Bar().但是,我不喜欢这样做因为我必须将Bar* bar指针保持在顶层,所以我可以delete在最后访问它,即使Bar是特定于特定代码块的东西if(whatever){}.

另一个解决方案是 …

c++ api reference-counting pass-by-reference shared-ptr

2
推荐指数
1
解决办法
395
查看次数

如何让策略类实现虚函数?

我正在尝试设计一个基于策略的类,其中某个接口由策略本身实现,因此该类派生自策略,它本身就是一个模板(我从Alexandrescu的书中得到了这种思考):

#include <iostream>
#include <vector>

class TestInterface {
public:
  virtual void test() = 0;
};

class TestImpl1 {
public:
  void test() {std::cerr << "Impl1" << std::endl;}
};

template<class TestPolicy>
class Foo : public TestInterface, TestPolicy {

};
Run Code Online (Sandbox Code Playgroud)

然后,在main()函数中,我test()(可能)调用所有实现相同接口的各种不同对象:

int main() {
  std::vector<TestInterface*> foos;
  foos.push_back(new Foo<TestImpl1>());
  foos[0]->test();
  delete foos[0];
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,它不会编译,因为

the following virtual functions are pure within ‘Foo<TestImpl1>’:
  virtual void TestInterface::test()
Run Code Online (Sandbox Code Playgroud)

我认为TestInterface::test()是实施的,因为我们来源于TestImpl1

c++ oop policy inheritance templates

2
推荐指数
1
解决办法
378
查看次数

为什么在虚函数中转换为Base类会产生分段错误?

我想用.打印出派生类operator<<.当我打印派生类时,我想首先打印它的基础,然后打印它自己的内容.

但是我遇到了一些麻烦(见下面的segfault):

class Base {
 public:
  friend std::ostream& operator<<(std::ostream&, const Base&);
  virtual void Print(std::ostream& out) const {
    out << "BASE!";
  }
};
std::ostream& operator<<(std::ostream& out, const Base& b) {
  b.Print(out);
  return out;
}

class Derived : public Base {
 public:
  virtual void Print(std::ostream& out) const {
    out << "My base: ";
    //((const Base*)this)->Print(out); // infinite, calls this fct recursively
    //((Base*)this)->Print(out);       // segfault (from infinite loop?)                                                          
    ((Base)*this).Print(out);          // OK
    out << " ... and myself.";
  }
};

int main(int …
Run Code Online (Sandbox Code Playgroud)

c++ virtual casting operator-overloading segmentation-fault

2
推荐指数
1
解决办法
796
查看次数